using AutoMapper;
using FluentValidation;
using Zhaoxi.Zhihu.Core.QuestionAggregate.Entites;
using Zhaoxi.Zhihu.Core.QuestionAggregate.Events;
using Zhaoxi.Zhihu.SharedKerel.Messaging;
using Zhaoxi.Zhihu.SharedKerel.Repositoy;
using Zhaoxi.Zhihu.SharedKerel.Result;
using Zhaoxi.Zhihu.UseCases.Common.Attributes;

namespace Zhaoxi.Zhihu.UseCases.Answers.Command;

[Authorize]
public record CreateAnswerCommand(int QuestionId, string Content):
    ICommand<Result<CreatedAnswerDto>>;


public class CreateAnswerCommandValidator : AbstractValidator<CreateAnswerCommand>
{
    public CreateAnswerCommandValidator()
    {
        RuleFor(command=> command. QuestionId)
            .GreaterThan(0);
        RuleFor(command=> command. Content)
            .NotEmpty();
    }
}

public class CreateAnswerComnandHandler(
    IRepository<Question> questions,
    IMapper mapper) : ICommandHandler<CreateAnswerCommand, Result<CreatedAnswerDto>>
{
    public async Task<Result<CreatedAnswerDto>> Handle(CreateAnswerCommand request, CancellationToken cancellationToken)
    {
        var question = await questions.GetByIdAsync(request. QuestionId, cancellationToken);
        
        if (question == null) return Result. NotFound("问题不存在");
        
        var answer = mapper.Map<Answer>(request);
        question.Answers.Add(answer);
        //调用实体添加事件
        answer.AddDomainEvent(new AnswerCreatedEvent(answer.QuestionId));
        await questions.SaveChangesAsync(cancellationToken);
        return Result.Success(new CreatedAnswerDto(question. Id, answer. Id));
    }
}


